package org.mirrentools.remoteattendance.admin;

import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.StringConverter;
import org.mirrentools.remoteattendance.admin.common.Requests;
import org.mirrentools.remoteattendance.admin.common.StringUtil;
import org.mirrentools.remoteattendance.admin.models.UserInfo;
import org.mirrentools.remoteattendance.admin.models.WorkRecordCVF;

import java.net.URL;
import java.time.LocalDate;
import java.util.*;

/**
 * 应用主控制器
 *
 * @author <a href="https://mirrentools.org">Mirren</a>
 */
public class MainController implements Initializable {
  /**
   * 最后一次异常的提醒时间
   */
  private long lastErrorTipsTime = 0;

  /**
   * 用户累计上班多少天
   */
  private final String COUNT_MONTH_TEMPLATE = "考勤月份: %s";
  /**
   * 用户累计上班多少天
   */
  private final String COUNT_DAYS_TEMPLATE = "工作总天数: %d 天,考勤要求%d天";
  /**
   * 用户累计上班多少小时
   */
  private final String COUNT_TIMES_TEMPLATE = "工作总时长: %s 小时";
  /**
   * 用户平均每天上班多少小时
   */
  private final String AVERAGE_TIMES_TEMPLATE = "平均每天工作: %s 小时";
  /**
   * 工作时长的字符串模板
   */
  private final String WORK_COUNT_TEMPLATE = "工作时长: %.2f小时";
  /**
   * 考勤日历中的Pane合集
   */
  private final Map<String, StackPane> stackPaneMap = new LinkedHashMap<>();
  /**
   * 用户选择列表
   */
  @FXML
  private ChoiceBox<UserInfo> choUsers;
  /**
   * 用户统计的月份
   */
  @FXML
  private Label lblCountMonth;
  /**
   * 用户累计上班多少天
   */
  @FXML
  private Label lblCountDays;
  /**
   * 用户累计上班多少小时
   */
  @FXML
  private Label lblCountTimes;
  /**
   * 用户平均每天上班多少小时
   */
  @FXML
  private Label lblAverageTimes;
  /**
   * 用户某一天的考勤记录
   */
  @FXML
  private AnchorPane panelDayRecordView;
  /**
   * 用户某一天的考勤时间
   */
  @FXML
  private Label lblWorkCount;

  /**
   * 某一天的考勤状态
   */
  @FXML
  private TextArea txtHistoryReport;
  @FXML
  private RadioButton radioHistoryNormal;
  @FXML
  private RadioButton radioHistoryLeave;
  @FXML
  private RadioButton radioHistoryOvertime;
  @FXML
  private RadioButton radioHistoryExchange;
  /**
   * 考勤详情
   */
  @FXML
  private TableView<WorkRecordCVF> tbWorkRecord;
  /**
   * 月份选择
   */
  @FXML
  private ChoiceBox<String> choMouths;
  /**
   * 日期表格
   */
  @FXML
  private GridPane gridPanel;
  /**
   * 历史考勤的视图
   */
  @FXML
  private AnchorPane panelHistoryAttendView;
  /**
   * 历史考勤正在加载中
   */
  @FXML
  private StackPane panelHistoryAttendLoading;


  /**
   * 最后选中用户
   */
  private UserInfo lastSelectUserInfo;
  /**
   * 最后选中的考勤日子
   */
  private String lastHistorySelectPaneId;

  @Override
  public void initialize(URL url, ResourceBundle resourceBundle) {
    try {
      initDatePanel(new ArrayList<>());
      initChoiceUsers();
      initChoiceMouths();
    } catch (Throwable e) {
      String tips = "执行初始化应用-->失败!";
      Logger.log(tips, e);
      showAlert(tips, 2);
      e.printStackTrace();
    }
  }

  /**
   * 初始化用户选择
   */
  private void initChoiceUsers() {
    choUsers.converterProperty().set(new StringConverter<>() {
      @Override
      public String toString(UserInfo userInfo) {
        String result = null;
        if (userInfo != null) {
          result = userInfo.nickname();
        }
        return result;
      }

      @Override
      public UserInfo fromString(String s) {
        return null;
      }
    });
    choUsers.setOnAction(e -> {
      SingleSelectionModel<UserInfo> model = choUsers.getSelectionModel();
      if (model != null) {
        this.lastSelectUserInfo = model.getSelectedItem();
        onMouthsSelect();
      }
    });
    Future<JsonObject> future = Requests.get(Requests.PATH_ADMIN_FIND_USERS);
    future.onSuccess(res -> {
      Logger.log("initChoiceUsers:" + res);
      JsonArray data = res.getJsonArray("data");
      if (data != null && !data.isEmpty()) {
        Platform.runLater(() -> {
          ObservableList<UserInfo> list = FXCollections.observableArrayList();
          for (int i = 0; i < data.size(); i++) {
            JsonObject d = data.getJsonObject(i);
            if (d != null && !d.isEmpty()) {
              String uid = d.getString("id");
              String nickname = d.getString("nickname");
              UserInfo userInfo = new UserInfo(uid, nickname);
              list.add(userInfo);
            }
          }
          choUsers.setItems(list);
        });
      }
    }).onFailure(err -> {
      String tips = "执行初始化考勤的月份选择-->失败!";
      Logger.log(tips, err);
      showAlert(tips, 2);
    });
  }

  /**
   * 初始化工作数据的表格
   *
   * @param mode 0=月份统计,1=每日统计
   */
  private void loadTableWorkRecord(int mode, ObservableList<WorkRecordCVF> items) {
    tbWorkRecord.getColumns().clear();
    String startTitle;
    String endTitle;
    String countTitle;
    if (mode == 0) {
      startTitle = "日期";
      endTitle = "工作时长";
      countTitle = "考勤报告";
    } else {
      startTitle = "工作时间";
      endTitle = "休息时间";
      countTitle = "工作时长";
    }
    TableColumn<WorkRecordCVF, String> start = new TableColumn<>(startTitle);
    start.setCellValueFactory(new PropertyValueFactory<>("start"));
    TableColumn<WorkRecordCVF, String> end = new TableColumn<>(endTitle);
    end.setCellValueFactory(new PropertyValueFactory<>("end"));
    TableColumn<WorkRecordCVF, String> count = new TableColumn<>(countTitle);
    count.setCellValueFactory(new PropertyValueFactory<>("wtime"));
    tbWorkRecord.getColumns().clear();
    tbWorkRecord.getColumns().add(start);
    tbWorkRecord.getColumns().add(end);
    tbWorkRecord.getColumns().add(count);
    tbWorkRecord.setPlaceholder(new Label("尚无工作记录"));
    tbWorkRecord.setColumnResizePolicy(resize -> {
      double width = resize.getTable().getWidth() - 20;
      if (mode == 0) {
        start.setPrefWidth(width * 0.2);
        end.setPrefWidth(width * 0.2);
        count.setPrefWidth(width * 0.6);
      } else {
        start.setPrefWidth(width / 3);
        end.setPrefWidth(width / 3);
        count.setPrefWidth(width / 3);
      }

      return true;
    });
    tbWorkRecord.setItems(items);
    if (mode == 0) {
      lblWorkCount.setText("");
    }
    panelDayRecordView.setVisible(true);
  }

  /**
   * 获取某一天的考勤数据
   *
   * @param year  年份
   * @param mouth 月份
   * @param day   日子 如果为0则不添加年月日
   */
  private void getWorkRecord(int year, int mouth, int day) {
    if (lastSelectUserInfo == null || StringUtil.isNullOrEmpty(lastSelectUserInfo.uid())) {
      return;
    }
    HttpRequest<Buffer> request = MainApplication.WEB_CLIENT.getAbs(Requests.PATH_FIND_DAYS_RECORD);
    if (day != 0) {
      this.panelHistoryAttendView.setVisible(false);
      this.panelDayRecordView.setVisible(false);
      this.panelHistoryAttendLoading.setVisible(true);
      request.addQueryParam("year", Integer.toString(year));
      request.addQueryParam("month", Integer.toString(mouth));
      request.addQueryParam("day", Integer.toString(day));
    }
    if (this.lastSelectUserInfo != null && !StringUtil.isNullOrEmpty(lastSelectUserInfo.uid())) {
      request.setQueryParam(Requests.NAME_FINAL_UID, lastSelectUserInfo.uid());
    }
    lblWorkCount.setText("正在加载中...");
    tbWorkRecord.getItems().clear();
    Future<JsonObject> future = Requests.request(request);
    future.onSuccess(res -> {
      try {
        JsonObject data = res.getJsonObject("data");
        Logger.log("getWorkRecord:" + data);
        if (data == null || data.isEmpty()) {
          return;
        }
        int state = StringUtil.getInteger(data.getInteger("state"), -1);
        String report = StringUtil.get(data.getString("report"), "");
        Long time = StringUtil.getLong(data.getLong("wtime"), 0L);
        float finalCount = Objects.equals(0L, time) ? 0 : ((float) time / 3600000L);
        Platform.runLater(() -> {
          if (day != 0) {
            lblWorkCount.setText(String.format(WORK_COUNT_TEMPLATE, finalCount));
            panelHistoryAttendLoading.setVisible(false);
            panelHistoryAttendView.setVisible(true);
            panelDayRecordView.setVisible(true);
            txtHistoryReport.setText(report);
            setSelectState(state);
          }
        });
        JsonArray items = data.getJsonArray("items");
        if (items != null && !items.isEmpty()) {
          Platform.runLater(() -> {
            ObservableList<WorkRecordCVF> lists = FXCollections.observableArrayList();
            for (int i = 0; i < items.size(); i++) {
              try {
                JsonObject d = items.getJsonObject(i);
                WorkRecordCVF cvf = new WorkRecordCVF();
                cvf.setStart(StringUtil.get(d.getString("start"), ""));
                cvf.setEnd(StringUtil.get(d.getString("end"), ""));
                Long w = StringUtil.getLong(d.getLong("wtime"), 0L);
                if (Objects.equals(0L, w)) {
                  cvf.setWtime("");
                } else {
                  float fc = Objects.equals(0L, w) ? 0f : ((float) w / 3600000L);
                  cvf.setWtime(String.format("%.2f", fc));
                }
                lists.add(cvf);
              } catch (Exception e) {
                String tips = "执行加载考勤记录-->失败!";
                Logger.log(tips, e);
                showAlert(tips, 2);
              }
            }
            loadTableWorkRecord(1, lists);
          });
        }
      } catch (Exception e) {
        String tips = "执行加载考勤记录-->失败!";
        Logger.log(tips, e);
        showAlert(tips, 2);
      }
    });
    future.onFailure(err -> {
      String tips = "执行获取考勤记录-->失败!";
      Logger.log(tips, err);
      showAlert(tips, 2);
    });

  }


  /**
   * 初始化月份选择
   */
  private void initChoiceMouths() {
    Future<JsonObject> future = Requests.get(Requests.PATH_FIND_CALENDAR_GROUP);
    future.onSuccess(res -> {
      Logger.log("initChoiceMouths:" + res);
      JsonArray data = res.getJsonArray("data");
      if (data != null && !data.isEmpty()) {
        Platform.runLater(() -> {
          ObservableList<String> list = FXCollections.observableArrayList();
          for (int i = 0; i < data.size(); i++) {
            JsonObject d = data.getJsonObject(i);
            if (d != null) {
              String m = d.getString("m");
              if (m != null && m.contains("-")) {
                list.add(m);
              }
            }
          }
          choMouths.setItems(list);
          choMouths.setOnAction(e -> onMouthsSelect());
          LocalDate now = LocalDate.now();
          String date = String.format("%s-%d", now.getYear(), now.getMonthValue());
          choMouths.getSelectionModel().select(date);
        });
      }
    }).onFailure(err -> {
      String tips = "执行初始化考勤的月份选择-->失败!";
      Logger.log(tips, err);
      showAlert(tips, 2);
    });
  }

  /**
   * 选择本月
   */
  public void choThisMouth() {
    LocalDate now = LocalDate.now();
    String date = String.format("%s-%d", now.getYear(), now.getMonthValue());
    choMouths.getSelectionModel().select(date);
  }

  /**
   * 选择上一个月
   */
  public void choPrevMouth() {
    LocalDate now = LocalDate.now();
    int year = now.getYear();
    int month = now.getMonthValue();
    String item = choMouths.getSelectionModel().getSelectedItem();
    if (item != null && item.contains("-")) {
      try {
        String[] split = item.split("-");
        year = Integer.parseInt(split[0].trim());
        month = Integer.parseInt(split[1].trim()) - 1;
      } catch (Exception e) {
        String tips = "执行加载选择上一个月的行事历-->失败!";
        Logger.log(tips, e);
        showAlert(tips, 2);
      }
    }
    if (month < 1) {
      year -= 1;
      month = 12;
    }
    String date = String.format("%s-%d", year, month);
    choMouths.getSelectionModel().select(date);
  }

  /**
   * 选择下一个月
   */
  public void choNextMouth() {
    LocalDate now = LocalDate.now();
    int year = now.getYear();
    int month = now.getMonthValue();
    String item = choMouths.getSelectionModel().getSelectedItem();
    if (item != null && item.contains("-")) {
      try {
        String[] split = item.split("-");
        year = Integer.parseInt(split[0].trim());
        month = Integer.parseInt(split[1].trim()) + 1;
      } catch (Exception e) {
        String tips = "执行加载选择下一个月的行事历-->失败!";
        Logger.log(tips, e);
        showAlert(tips, 2);
      }
    }
    if (month > 12) {
      year += 1;
      month = 1;
    }
    String date = String.format("%s-%d", year, month);
    choMouths.getSelectionModel().select(date);
  }

  /**
   * 月份选中事件
   */
  public void onMouthsSelect() {
    SingleSelectionModel<String> model = choMouths.getSelectionModel();
    String s = model.getSelectedItem();
    if (!s.contains("-")) {
      return;
    }
    panelHistoryAttendView.setVisible(false);
    String[] split = s.split("-");
    LocalDate now = LocalDate.now();
    int year = StringUtil.getInteger(split[0].trim(), now.getYear());
    int month = StringUtil.getInteger(split[1].trim(), now.getMonthValue());
    MultiMap query = MultiMap.caseInsensitiveMultiMap();
    query.add("year", Integer.toString(year));
    query.add("month", Integer.toString(month));
    boolean isInitU = true;//是否为初始化不显示用户的考勤状态
    if (this.lastSelectUserInfo != null && !StringUtil.isNullOrEmpty(lastSelectUserInfo.uid())) {
      query.add(Requests.NAME_FINAL_UID, lastSelectUserInfo.uid());
      isInitU = false;
      // 加载用户当月的考勤
      Future<JsonObject> future = Requests.get(Requests.PATH_FIND_MONTH_RECORD, query);
      future.onSuccess(res -> {
        Logger.log("onUsersSelect:" + res);
        Platform.runLater(() -> {
          JsonObject data = res.getJsonObject("data");
          Integer userDays = data.getInteger("days");
          Integer workDays = data.getInteger("workd");
          String workTime;
          Long w = StringUtil.getLong(data.getLong("wtime"), 0L);
          String avgTime;
          if (Objects.equals(0L, w)) {
            workTime = "0";
            avgTime = "0";
          } else {
            float fc = Objects.equals(0L, w) ? 0f : ((float) w / 3600000L);
            workTime = String.format("%.2f", fc);
            avgTime = String.format("%.2f", fc / userDays);
          }
          lblCountMonth.setText(String.format(COUNT_MONTH_TEMPLATE, year + "-" + month));
          lblCountDays.setText(String.format(COUNT_DAYS_TEMPLATE, userDays, workDays));
          lblCountTimes.setText(String.format(COUNT_TIMES_TEMPLATE, workTime));
          lblAverageTimes.setText(String.format(AVERAGE_TIMES_TEMPLATE, avgTime));
          JsonArray records = data.getJsonArray("records");
          LinkedHashMap<Integer, WorkRecordCVF> map = new LinkedHashMap<>();
          if (records != null && !records.isEmpty()) {
            for (int i = 0; i < records.size(); i++) {
              JsonObject d = records.getJsonObject(i);
              WorkRecordCVF cvf = new WorkRecordCVF();
              Integer days = d.getInteger("days");
              cvf.setStart(Integer.toString(days));
              Long wtime = StringUtil.getLong(d.getLong("wtime"), 0L);
              if (Objects.equals(0L, wtime)) {
                cvf.setEnd("0小时");
              } else {
                float fc = Objects.equals(0L, wtime) ? 0f : ((float) wtime / 3600000L);
                cvf.setEnd(String.format("%.2f小时", fc));
              }
              map.put(days, cvf);
            }
            JsonArray reports = data.getJsonArray("reports");
            if (reports != null && !reports.isEmpty()) {
              for (int i = 0; i < reports.size(); i++) {
                JsonObject d = reports.getJsonObject(i);
                Integer days = d.getInteger("days");
                if (map.get(days) != null) {
                  Integer state = d.getInteger("state");
                  String report = StringUtil.get(d.getString("report"), "");
                  if (Objects.equals(0, state)) {
                    report = "【全勤】" + report;
                  } else if (Objects.equals(1, state)) {
                    report = "【请假】" + report;
                  } else if (Objects.equals(2, state)) {
                    report = "【加班】" + report;
                  } else if (Objects.equals(3, state)) {
                    report = "【调补班】" + report;
                  }
                  map.get(days).setWtime(report);
                }
              }
            }
          }
          ObservableList<WorkRecordCVF> cvfs = FXCollections.observableList(new ArrayList<>(map.values()));
          loadTableWorkRecord(0, cvfs);
        });
      });
      future.onFailure(err -> {
        String tips = "执行选择考勤:" + year + "-" + month + "-->失败!";
        Logger.log(tips, err);
        showAlert(tips, 2);
      });

    }
    Future<JsonObject> future = Requests.get(Requests.PATH_FIND_CALENDAR, query);
    boolean finalIsInitU = isInitU;
    future.onSuccess(res -> {
      Logger.log("onMouthsSelect:" + res);
      JsonArray data = res.getJsonArray("data");
      List<JsonObject> items = new ArrayList<>();
      for (int i = 0; i < data.size(); i++) {
        JsonObject d = data.getJsonObject(i);
        if (finalIsInitU) {
          d.put("u", -1);
        }
        items.add(d);
      }
      initDatePanel(items);
    });
    future.onFailure(err -> {
      String tips = "执行选择考勤:" + year + "-" + month + "-->失败!";
      Logger.log(tips, err);
      showAlert(tips, 2);
    });
  }

  /**
   * 初始化行事历以及用户的考勤统计
   *
   * @param items ys(int):年份,ms(int):月份,ds(int):日子,w(int):是否需要上班,u(int):用户是否上班
   */
  private void initDatePanel(List<JsonObject> items) {
    Platform.runLater(() -> {
      gridPanel.getChildren().clear();
      stackPaneMap.clear();
      initDatePanelTitle();
      if (items.isEmpty()) {
        StackPane pane = new StackPane();
        pane.getChildren().add(new Label("尚无数据"));
        gridPanel.add(pane, 0, 1);
        return;
      }
      int index = 0;
      int maxIndex = items.size();
      int startDay = getStartDay(items.get(0));
      for (int row = 1; row < 7; row++) {
        for (int col = 0; col < 7; col++) {
          if (index >= maxIndex) {
            break;
          }
          String paneId = row + "-" + col;
          StackPane pane = new StackPane();
          pane.setId(paneId);
          if (startDay > 0) {
            startDay--;
            gridPanel.add(pane, col, row);
            continue;
          }
          try {
            JsonObject data = items.get(index++);
            pane.setUserData(data);
            Integer days = StringUtil.getInteger(data.getInteger("ds"), index);
            Integer w = StringUtil.getInteger(data.getInteger("w"), 0);
            Integer u = StringUtil.getInteger(data.getInteger("u"), 0);
            pane.setBackground(new Background(new BackgroundFill(Color.WHITE, null, null)));
            Label day = new Label(Integer.toString(days));
            StackPane.setAlignment(day, Pos.TOP_CENTER);
            day.setAlignment(Pos.CENTER);
            day.setPadding(new Insets(8, 10, 8, 10));
            Label sys = new Label("");
            if (Objects.equals(1, w)) {
              sys.setBackground(new Background(new BackgroundFill(Color.rgb(0, 220, 0), null, null)));
            }
            StackPane.setAlignment(sys, Pos.BOTTOM_LEFT);
            sys.setPadding(new Insets(4, 10, 4, 10));
            Label usr = new Label("");
            if (Objects.equals(0, u)) {
              usr.setBackground(new Background(new BackgroundFill(Color.rgb(0, 220, 0), null, null)));
            } else if (Objects.equals(1, u)) {
              usr.setBackground(new Background(new BackgroundFill(Color.rgb(245, 108, 108), null, null)));
            } else if (Objects.equals(2, u)) {
              usr.setBackground(new Background(new BackgroundFill(Color.rgb(64, 158, 255), null, null)));
            } else if (Objects.equals(3, u)) {
              usr.setBackground(new Background(new BackgroundFill(Color.rgb(230, 162, 60), null, null)));
            }
            usr.setPadding(new Insets(4, 10, 4, 10));
            StackPane.setAlignment(usr, Pos.BOTTOM_RIGHT);
            pane.getChildren().addAll(day, sys, usr);
            pane.widthProperty().addListener(r -> {
              double width = pane.getWidth();
              day.setPrefWidth(width);
              sys.setPrefWidth(width / 2);
              usr.setPrefWidth(width / 2);
            });
            pane.setOnMouseClicked(e -> selectAttendHandler(paneId, data));
            stackPaneMap.put(paneId, pane);
            gridPanel.add(pane, col, row);
            setAttendPaneBorder(lastHistorySelectPaneId);
          } catch (Exception e) {
            String tips = "执行初始化行事历-->失败!";
            Logger.log(tips, e);
            showAlert(tips, 2);
          }
        }
      }
    });
  }

  /**
   * 考勤日历选中指定内容的事件处理器
   *
   * @param data 考勤日历数据
   */
  private void selectAttendHandler(String paneId, JsonObject data) {
    setAttendPaneBorder(paneId);
    Integer ys = data.getInteger("ys");
    Integer ms = data.getInteger("ms");
    Integer ds = data.getInteger("ds");
    lastHistorySelectPaneId = paneId;
    getWorkRecord(ys, ms, ds);
  }

  /**
   * 给选中的行事历加上边框
   *
   * @param paneId pane的id
   */
  private void setAttendPaneBorder(String paneId) {
    if (paneId == null) {
      return;
    }
    stackPaneMap.forEach((k, v) -> {
      if (Objects.equals(k, paneId)) {
        v.setStyle("-fx-border-color:red");
      } else {
        v.setStyle("-fx-border-color:none");
      }
    });
  }

  /**
   * 获取日期在星期几
   *
   * @param data ys=年,ms=月,ds=天
   */
  public int getStartDay(JsonObject data) {
    Integer ys = data.getInteger("ys");
    Integer ms = data.getInteger("ms");
    Integer ds = data.getInteger("ds");
    LocalDate localDate = LocalDate.of(ys, ms, ds);
    return localDate.getDayOfWeek().getValue();
  }

  /**
   * 初始化行事历与考勤的日历标题
   */
  private void initDatePanelTitle() {
    for (int i = 0; i < 7; i++) {
      StackPane pane = new StackPane();
      pane.setAlignment(Pos.CENTER);
      pane.setBackground(new Background(new BackgroundFill(Color.WHITE, null, null)));
      Label title = new Label();
      switch (i) {
        case 0 -> {
          title.setText("日");
          title.setTextFill(Color.RED);
        }
        case 1 -> title.setText("一");
        case 2 -> title.setText("二");
        case 3 -> title.setText("三");
        case 4 -> title.setText("四");
        case 5 -> title.setText("五");
        case 6 -> title.setText("六");
      }
      pane.getChildren().add(title);
      gridPanel.add(pane, i, 0);
    }
  }


  /**
   * 更新考勤状态
   *
   * @param state 状态:0=全勤,1=请假,2=加班,3=调班补班
   */
  private void setSelectState(int state) {
    if (state == 1) {
      radioHistoryLeave.setSelected(true);
    } else if (state == 2) {
      radioHistoryOvertime.setSelected(true);
    } else if (state == 3) {
      radioHistoryExchange.setSelected(true);
    } else {
      radioHistoryNormal.setSelected(true);
      if (state != 0) {
        radioHistoryNormal.setSelected(false);
      }
    }
  }

  /**
   * 显示消息弹窗
   *
   * @param msg  信息
   * @param type 弹窗的类型,0=普通提醒,1=警告提醒,2=异常
   */
  private void showAlert(String msg, int type) {
    MainApplication.showAlert(msg, type);
  }

}